package com.tour.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.tour.config.ResponseWrapper;
import com.tour.entity.FComment;
import com.tour.entity.Restaurant;
import com.tour.mapper.FCommentMapper;
import com.tour.mapper.RestaurantMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lel
 * @since 2021-03-30
 */
@Service
public class FCommentServiceImpl extends ServiceImpl<FCommentMapper, FComment> implements IService<FComment> {

    @Autowired
    FCommentMapper commentMapper;
    @Autowired
    RestaurantMapper restaurantMapper;

    public ResponseWrapper addsComment(FComment fComment){
        if (fComment == null){
            return ResponseWrapper.markError();
        }else {
            int result = commentMapper.insert(fComment);
            if (result == 1){
                Restaurant restaurant = restaurantMapper.selectById(fComment.getRId());
                QueryWrapper<FComment> fCommentQueryWrapper = new QueryWrapper<>();
                fCommentQueryWrapper.eq("r_id",fComment.getRId());
                List<FComment> commentList = commentMapper.selectList(fCommentQueryWrapper);
                int score = 0;
                for (FComment comment : commentList){
                    System.out.println("------");
                    score +=Integer.valueOf(comment.getShopScore());
                }
                System.out.println(score);
                DecimalFormat df = new DecimalFormat("0.0");
                float scores = Float.valueOf(df.format(score));
                float relscore = Float.valueOf(scores/commentList.size());
                String relscores = df.format(relscore);
                restaurant.setShopScore(relscores);
                restaurantMapper.updateById(restaurant);
                return ResponseWrapper.markSuccess(null);
            }else {
                return ResponseWrapper.markError();
            }
        }
    }

    public ResponseWrapper deleteComment(Integer fcid){
        if (fcid == null){
            return ResponseWrapper.markError();
        }else {
            int result = commentMapper.deleteById(fcid);
            if (result == 1){
                return ResponseWrapper.markSuccess(null);
            }else {
                return ResponseWrapper.markError();
            }
        }
    }

}
